#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <vector>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "netaddr.hpp"
#include "ThreadPool.hpp"
#include "SmartMutex.hpp"
#include "Log.hpp"

using namespace std;

class Server
{
public:
    Server(uint16_t port) : _port(port)
    {
        pthread_mutex_init(&_user_mutex, nullptr);
    }

    void Init()
    {
        // 创建网络文件信息
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            exit(1);
        }
        LOG(Debug, "创建socket文件成功\n");

        struct sockaddr_in addr;
        memset(&addr, 0, sizeof(addr));
        // addr.sin_addr.s_addr = inet_addr(_ip.c_str());
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_port = htons(_port);
        addr.sin_family = AF_INET;

        int n = bind(_sockfd, (struct sockaddr *)&addr, sizeof(addr));
        if (n < 0)
        {
            exit(2);
        }
        LOG(Debug, "bind成功\n");


        tp.Start();
    }

    void CheckUser(netaddr &user)
    {
        for (auto u : _users) // 检查用户是否重复插入
        {
            if (u == user) // 这里需要对netaddr类进行运算符重载
            {
                return;
            }
        }
        _users.push_back(user);
        LOG(Debug, "添加用户：%s\n", CSTR(user.SockInfo()));

    }

    using task_t = function<void()>;

    void Route(netaddr &senduser, const string &msg)
    {
        SmartMutex smartMutex(&_user_mutex);
        string message = senduser.SockInfo();
        message += "# ";
        message += msg;
        for (auto u : _users)
        {
            if (!(u == senduser))
            {
                sendto(_sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&u.GetAddr(), sizeof(u.GetAddr()));
                LOG(Debug, "%s ：发送消息给：%s\n", CSTR(senduser.SockInfo()), CSTR(message));

            }
        }
    }

    void Start()
    {
        for (;;)
        {
            char buffer[1024];
            struct sockaddr_in addr;
            socklen_t len = sizeof(addr);
            // 接收客户端消息
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&addr, &len);
            if (n > 0)
            {
                // 对用户进行记录
                netaddr user(addr);
                CheckUser(user);

                buffer[n] = 0;
                string msg = buffer;
                task_t t = bind(&Server::Route, this, user, msg);
                tp.Push(t);
                // cout << "Client say# " << buffer << endl;
                // n = sendto(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&addr, len);
            }
        }

        close(_sockfd);
    }

    ~Server()
    {
        pthread_mutex_destroy(&_user_mutex);
    }

private:
    int _sockfd;
    uint16_t _port;

    ThreadPool<task_t> tp;
    vector<netaddr> _users;

    pthread_mutex_t _user_mutex;
};